/**
 * 病种入组病例管理初始化
 */
var SdsCustomGroup = {
    id: "SdsCustomGroupTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    hospID: null,
    episodeId: 0,
    clicked: false,
    checkPerm: $("#checkPerm").val(), // 审核权限
    submitPerm: $("#submitPerm").val(), // 填报权限
    docUpPerm: $("#formCheckType").val(), // 医生能否直接上报配置
    enableIPQC: $("#enableIPQC").val() // 是否启用过程质控
};

/**
 * 初始化表格的列
 */
SdsCustomGroup.initColumn = function () {
    var columnArr = [
        {
            width: 30, align: "center", valign: 'middle', sortable: true, formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize = $('#SdsCustomGroupTable').bootstrapTable('getOptions').pageSize;
                //获取当前是第几页
                var pageNumber = $('#SdsCustomGroupTable').bootstrapTable('getOptions').pageNumber;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        },
        {title: '院区', field: 'admHospDesc', width: 120, align: 'left', valign: 'middle'},
        {title: '科室', field: 'admLocDesc', width: 120, align: 'left', valign: 'middle'},
        {title: '病案号', field: 'mrNum', width: 100, align: 'left', valign: 'middle'},
        {title: '就诊号', field: 'id', width:100, align: 'left', valign: 'middle'},
        {title: '姓名', field: 'name', width: 100, align: 'left', valign: 'middle'},
        {title: '性别', field: 'sex', width: 30, align: 'center', valign: 'middle'},
        {title: '年龄', field: 'age', width: 30, align: 'center', valign: 'middle'},
        {title: '主管医生', field: 'admDocName', width: 80, align: 'left', valign: 'middle'},
        {title: '入院日期', field: 'admDate', width: 120, align: 'left', valign: 'middle'},
        {title: '出院日期', field: 'dishDate', width: 120, align: 'left', valign: 'middle'},
        {title: '病种名称', field: 'entityName', width: 140, align: 'left', valign: 'middle'},
        {
            title: '操作',
            field: 'id',
            align: 'center',
            width: '80px',
            valign: 'middle',
            formatter: function (value, row, index) {
                return '<a href="javascript:SdsCustomGroup.del(\'' + row.customId + '\',\'' + row.entityId + '\')" title="排除"><i class="hisui-icon icon-cancel"></i></a>';
            }
        }];

    return columnArr;
};

/**
 * 检查是否选中
 */
SdsCustomGroup.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Sys.info("请先选中表格中的某一记录！");
        return false;
    } else {
        SdsCustomGroup.seItem = selected[0];
        return true;
    }
};

/**
 * 删除病种入组病例
 */
SdsCustomGroup.del = function (id, entityId) {
    var flag = false;
    if (id) {
        flag = true;
    } else if (this.check()) {
        id = this.seItem.id;
        entityId = this.seItem.entityId;
        flag = true;
    }
    if (flag) {
        //打开 弹出框
        var index = layer.open({
            type: 2,
            title: ['排除自定义病种【信息录入】'],
            area: ['400px', '250px'],
            zIndex: 19911102,//这是个大坑！！！！ 默认是19891014 远远大于量表下拉框的zIndex 导致下拉框的数据看不到！！！
            content: "/sds/sdscusmrlist/excludeindex?mrListId=" + id + "&entityId=" + entityId,
            skin: 'layer-ext-hisui',
            scrollbar: false//为了禁止父页面滚动条滚动
        });
        this.layerIndex = index;

        //监听子页面的postMessage
        function receiveMessage(event) {
            //取得子页面传回来的值
            if (event.data == "close") {
                // 如果传回close，关闭当前弹窗
                layer.close(index);
            }
            if (event.data == "save") {
                SdsCustomGroup.table.refresh();
                setTimeout(function () {
                    layer.close(index);
                }, 1000);
            }
        }

        window.addEventListener('message', receiveMessage, false);
    }
};


function Common_CheckboxToSDRule() {
    var ItemCode = arguments[0];
    var ParRef = arguments[1];
    var RuleType = arguments[2];
    var columns = arguments[3] ? arguments[3] : 4;
    var params = {};
    var ajax = new $ax(Sys.backendPath + "/sds/sdsopqcincase/selectRulesByQcEntityId", function (data) {
        //加载表格数据
        var dicList = data.split(";");
        if (dicList[0] == "") {
            $('#' + ItemCode).html("");
            return;
        }
        var len = dicList.length;
        var count = parseInt(len / columns) + 1;
        var per = Math.round((1 / columns) * 100) + '%';  //每列所在百分比，等比分布

        var listHtml = ""
        for (var index = 0; index < count; index++) {
            var chklen = (((index + 1) * columns) < len) ? (index + 1) * columns : len;
            listHtml += "<div style='width: 90%;'>";
            for (var dicIndex = index * columns; dicIndex < chklen; dicIndex++) {
                var dicSubList = dicList[dicIndex].split(",");

                listHtml += "<input id=" + ItemCode + dicSubList[0] + " type='checkbox' class='hisui-checkbox' " + (dicSubList[0] == 1 ? "checked='true'" : "") + " label= '" + dicSubList[1] + "'  name=" + ItemCode + "  value=" + dicSubList[0] + ">";
            }
            listHtml += "</div>"
        }
        $('#' + ItemCode).html(listHtml);
        $.parser.parse('#' + ItemCode);  //解析checkbox
    }, function (data) {
    });
    params.qcEntityId = ParRef;
    params.ruleType = RuleType;
    ajax.set(params);
    ajax.start();
}

function Common_SetValue() {
    var itmValue = '';

    var val = arguments[1];
    var txt = arguments[2];

    if (typeof (arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#' + arguments[0]);
    if ($this.length < 1) return '';
    if (typeof val == 'undefined') val = '';
    if (typeof txt == 'undefined') txt = '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val(val);
    } else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val(val);
    } else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('setValue', val);
    } else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('setValue', val);
    } else if (className == 'hisui-combobox') {  //下拉框
        if (val != "" && txt == "") {
            itmValue = $this.combobox('setValue', val);
        } else {
            itmValue = $this.combobox('setValue', txt);
        }
    } else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('setValue', val);
    } else if (className == 'hisui-checkbox') {  // 单个复选框
        if (val == '') val = 0;
        itmValue = $this.checkbox('setValue', (val) ? true : false);
    } else if (className == 'hisui-radio') {  //单个单选框
        if (val == '') val = 0;
        itmValue = $this.radio('setValue', (val) ? true : false);
    } else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('setValue', val);
    }

    return itmValue;
}

function Common_GetValue() {
    var itmValue = '';

    if (typeof (arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#' + arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    } else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    } else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    } else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    } else if (className == 'hisui-combobox') {  //下拉框（多选下拉框没有封装）
        itmValue = $this.combobox('getValue');
    } else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    } else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.checkbox('getValue');
    } else if (className == 'hisui-radio') {  //单个单选框
        itmValue = $this.radio('getValue');
    } else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}

function Common_CheckboxValue() {
    var ItemCode = arguments[0];
    var value = "";
    $("input[name='" + ItemCode + "']:checked").each(function () {
        value = value + $(this).val() + ",";
    });
    if (value != "") {
        value = value.substring(0, value.length - 1);
    }

    return value;
}

$("#hosp").combobox({
    onSelect:function (rec){
        var hospId = rec.value
        $("#hosp").combobox("select",hospId)
        var ajax = new $ax(Sys.backendPath + "/sds/common/deptListByHospId", function (data) {
            $('#dept').combobox({
                data:data,
                valueField:'value',
                textField:'text',
                defaultFilter: 6,
                onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                    $(this).combobox("setValue", "");
                }
            });
        },function(data){
            layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
        })
        ajax.set({"hospID":hospId,"id":"depart"});
        ajax.start();
    }
})

/**
 * 查询病种入组病例列表
 */
SdsCustomGroup.search2 = function () {
    //出院日期
    var startDate = $('#startDate1').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate1').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    var dept = $('#dept').combobox('getValue');
    var hosp = $('#hosp').combobox('getValue');
    var mrNum = $("#mrNum").val();
    var epNum = $("#epNum").val();
    var name = $("#name").val();
    var admDoctorName = $("#admDoctorName").val();
    var entityId = $("#entityId").combobox("getValue");
    SdsCustomGroup.search(startDate, endDate, epNum, mrNum, name, admDoctorName, dept, hosp, entityId);
};

SdsCustomGroup.clear = function () {
    $("#name").val('');
    $("#admDoctorName").val('');
    $("#mrNum").val('');
    $("#epNum").val('');
    $("#dept").combobox("setValue", "");
    $("#hosp").combobox("setValue", "");
    $("#entityId").combobox("setValue", "");
}

SdsCustomGroup.search = function (startDate, endDate, epNum, mrNum, name, admDoctorName, dept, hosp, entityId) {
    var queryData = {};
    queryData['startDate'] = startDate;
    queryData['endDate'] = endDate;
    queryData['epNum'] = epNum;
    queryData['mrNum'] = mrNum;
    queryData['name'] = name;
    queryData['admDoctorName'] = admDoctorName;
    queryData['admLocId'] = dept;
    queryData['hosp'] = hosp;
    queryData['entityId'] = entityId
    SdsCustomGroup.table.refresh({query: queryData, pageNumber: 1});
};

/**
 * 导出数据-不同条件
 */
SdsCustomGroup.exportExcel = function (){

    var startDate = $('#startDate1').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate1').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    var hosp = $('#hosp').combobox('getValue');
    var dept = $('#dept').combobox('getValue');
    var epNum = $("#epNum").val();
    var mrNum = $("#mrNum").val();
    var name = $("#name").val();
    var admDoctorName = $("#admDoctorName").val();
    var entityId = $("#entityId").combobox("getValue");

    var queryData = {};
    queryData['startDate'] = startDate;
    queryData['endDate'] = endDate;
    queryData['hosp'] = hosp;
    queryData['epNum'] = epNum;
    queryData['mrNum'] = mrNum;
    queryData['name'] = name;
    queryData['admDoctorName'] = admDoctorName;
    queryData['admLocId'] = dept;
    queryData['entityId'] = entityId


    var longStart = Date.parse(startDate);
    var longEnd = Date.parse(endDate);
    if(longStart>longEnd){
        Sys.error("开始日期不可大于结束日期");
        return false;
    }

    Sys.loading("数据文件生成中,请耐心等待");
    var ajax = new $ax(Sys.backendPath + "/sds/sdscusmrlist/createExcel", function(data){
        Sys.closeLoading();
        if(data.message=="DHCC"){
            Sys.info("无数据可以导出，请更改查询条件。");
        }else{
            window.location.href = Sys.backendPath + "/sds/sdscusmrlist/excelDown/"+data.message;
            SdsCustomGroup.table.refresh({query: queryData, pageNumber: 1});
        }
    },function(data){
        Sys.error("数据生成失败!" + data.responseJSON.message + "!");
    });
    ajax.set(queryData);
    ajax.setAsync(true);
    ajax.start();
}


$(function () {
    $('#winConfirmInfo').dialog({
        title: '',
        iconCls: "icon-w-edit",
        closed: true,
        modal: true,
        isTopZindex: true
    });
    var startDate = $('#startDate1').datebox('getValue');//开始日期
    startDate = startDate + " 00:00:00";
    var endDate = $('#endDate1').datebox('getValue');//结束日期
    endDate = endDate + " 23:59:59";
    var dept = $('#dept').datebox('getValue');

    var defaultColunms = SdsCustomGroup.initColumn();
    var table = new BSTable(SdsCustomGroup.id, Sys.backendPath + "/sds/sdscusmrlist/list", defaultColunms);
    table.setPaginationType("server");
    table.setPageSize(15);
    table.setShowRefresh(false);
    table.setShowColumns(false);
    table.setShowToggle(false);
    table.setShowExport(false);
    var b_height = document.documentElement.clientHeight;
    table.setHeight(b_height - 180);
    table.set("startDate", startDate);
    table.set("endDate", endDate);
    table.set("dept", dept);
    SdsCustomGroup.table = table.init();
});

//在Jquery里格式化Date日期时间数据
function timeStamp2String(time) {
    var datetime = new Date();
    datetime.setTime(time);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    return year + "-" + month + "-" + date;
}
